<template>
  <el-dialog v-model="off.dialog" :title="uploadForm.dialogTitle" draggable :close-on-click-modal="false"
    :close-on-press-escape="false" width="550px" @close="handleCancel">
    <el-form :model="formData" :rules="rules" ref="formRef">
      <div style="text-align:center;margin-bottom: 10px;color: #7f7f82;">
        <p>{{ uploadForm.tips || '你可以上传xls、xlsx格式的文件，文件大小请勿超过6M' }}</p>
        <!-- <p>(为保证文件上传成功，建议先下载模板，按模板示范格式填写完成后再上传文件)</p> -->
      </div>
      <el-upload class="f-upload" ref="upload" drag :action="form.action" :data="form.data" :headers="form.headers"
        :auto-upload="false" :limit="2" :accept="uploadForm.accept || ''" :on-success="handleSuccessUpload"
        :on-error="handleErrorUpload" :on-change="handleChangeUpload">
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>

      <template #tip>
        <div v-if="tip" class="el-upload__tip" style="color:red">
          {{tip}}
        </div>
      </template>
      <!-- <el-divider /> -->
      <!-- <el-form-item prop="password">
        <div style="width:100%;">
          <el-input style="width:100%;" maxlength="20" placeholder="为了确保本次操作的安全性，请输入登录密码" type="password"
            v-model="formData.password" show-password @keyup.enter="handleSave" />
        </div>
      </el-form-item> -->
      <!-- <el-form-item prop="time" v-if="uploadForm.seletMonth">
        <div style="width:100%;">
          <el-date-picker style="width:100%;" v-model="formData.time" type="month" placeholder="请选择" @change="seletMonth" />
        </div>
      </el-form-item> -->
      <el-form-item prop="title" v-if="uploadForm.title" label="标题">
        <div style="width:100%;">
          <el-input style="width:100%;" placeholder="请输入" v-model="formData.title" />
        </div>
      </el-form-item>
      <el-form-item prop="description " v-if="uploadForm.description" label="描述">
        <div style="width:100%;">
          <el-input style="width:100%;" type="textarea" placeholder="请输入" v-model="formData.description" />
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <!-- <a class="pointer" @click="downLoadTemplate('stencil')">
          下载模板
        </a> -->
        <div style="display:flex;">
          <el-button size="small" @click="handleCancel" :disabled="off.loading">取消</el-button>
          <el-button size="small" type="primary" @click="handleSave" :loading="off.loading">
            上传
            <span v-show="off.loading">中...</span>
          </el-button>
        </div>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, toRefs, onMounted } from 'vue'
import { getStore, errorDeal, BlobDownLoad, getDateTime, } from '@/utils/utils'
import { ElNotification } from "element-plus";
import hexMD5 from "@/utils/md5.min.js";
import api from "./api";

export default {
  props: ['uploadForm'],
  emits: ["handleUploadSuccess", "handleUploadCancel"],

  setup(props, context) {
    const confirmPassword = async (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入登录密码！"));
      } else {
        let res = await confirmPwd()
        if (res) {
          callback()
        } else {
          callback('登录密码错误!')
        }
      }
    };

    const formRef = ref(null)
    const state = reactive({
      userInfo: {},
      off: {
        dialog: false,
        loading: false
      },
      form: {
        action: props.uploadForm.action,
        headers: {
          Authorization: getStore('USER_AUTHOR_INRE').Authorization || `'','','',3,20,''`,
          Token: `Bearer ${window.localStorage.getItem("USER_TOKEN_INRE")}`,
          platformHeadType: 'rcmsPlatform'
        },
        data: {}
      },

      formData: {},

      rules: {
        password: [
          {
            validator: confirmPassword,
            trigger: "blur",
            required: true,
          },
        ],
        time: [
          { required: true, message: '请选择月份', trigger: 'change' },
        ],
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
        ],
      },
      upload: "",
      tip: "",
      uploadFiles: [],
      uploadForm: props.uploadForm
    })

    onMounted(() => {
      state.userInfo = getStore('USER_INFO_INRE')
    })

    const handleSuccessUpload = (res, file, fileList) => {
      let type = ""
      if (res.code == 200) {
        type = 'success'
        state.off.dialog = false
        context.emit('handleUploadSuccess')
      } else {
        type = 'error'
      }
      ElNotification({
        title: '提示',
        message: res.msg,
        type: type,
      })
      state.off.loading = false
      state.tip = ""
      state.formData = {}
      state.upload.clearFiles()
      formRef.value.resetFields()
    }

    const handleErrorUpload = (err, file, fileList) => {
      state.off.loading = false
      state.tip = ""
      state.formData = {}
      ElNotification({
        title: '提示',
        message: err.msg,
        type: 'error',
      })
      state.upload.clearFiles()
      formRef.value.resetFields()
    }

    const handleChangeUpload = (file, fileList) => {
      state.uploadFiles = fileList
      state.tip = ""
      if (fileList.length > 1) {
        fileList.splice(0, 1);
      }
    }

    const handleCancel = () => {
      state.off.dialog = false
      state.off.loading = false
      state.tip = ""
      state.formData = {}
      state.uploadFiles = []
      state.upload.clearFiles()
      formRef.value.resetFields()
      context.emit('handleUploadCancel')
    }

    const handleSave = () => {
      if (state.uploadFiles.length) {
        formRef.value.validate((valid) => {
          if (valid) {
            state.off.loading = true
            state.tip = ""
            state.form.data = state.formData
            if (state.uploadForm.id) {
              state.form.data.id = state.uploadForm.id
            }
            state.upload.submit()
          }
        })
      } else {
        errorDeal("请选择上传文件！")
      }
    }

    //密码校验
    function confirmPwd() {
      return new Promise((resolve, reject) => {
        let json = {
          password: hexMD5(state.formData.password),
          userId: state.userInfo.userId
        };
        api.confirmPwd(json).then(res => {
          if (res.code == '200') {
            resolve(true)
          } else {
            resolve(false)
          }
        }).catch(err => {
          reject('登录密码错误!')
        })
      })
    }

    const downLoadTemplate = (v, m) => {
      let json = {
        responseType: "blob"
      }
      api.userDownload(json).then((res) => {
        const fileName = decodeURI(res.headers["content-disposition"].split(";")[1].split("=")[1]) || "text.xlsx";
        BlobDownLoad(res, fileName);
      });
    }

    const seletMonth = (e) => {
      let time = getDateTime(e.getTime())
      state.form.data = {
        "month": time[1],
        "year": time[0]
      }
    }

    return {
      ...toRefs(state),
      formRef,
      handleSuccessUpload,
      handleErrorUpload,
      handleChangeUpload,
      handleCancel,
      handleSave,
      downLoadTemplate,
      seletMonth
    }
  }
}
</script>

<style lang="scss" scoped>
.f-upload {
  text-align: center;
  padding-bottom: 20px;
}

.print {
  height: 20px;
  width: 20px;
  position: absolute;
  right: 15px;
  top: 6px;
  z-index: 2;
  color: #999;
}
.dialog-footer {
  display: flex;
  justify-content: right;
}
</style>
